package com.lxf.cloudotherserve.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.lxf.cloudfeign.client.productClient.ProductClient;
import com.lxf.cloudfeign.client.userClient.UserClient;
import com.lxf.cloudotherserve.bean.UserCLRBean;
import com.lxf.cloudotherserve.mapper.UserCLRItemRepository;
import com.lxf.cloudotherserve.mapper.UserCLRMapper;
import com.lxf.cloudotherserve.service.BaseStrategy;
import com.lxf.cloudotherserve.service.UserCLRService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author 罗兴发
 * @data 2025/6/30 14:42
 * @description：用户点赞/收藏/转发-业务实现层
 */
@Service
@Slf4j
public class UserCLRServiceImpl implements UserCLRService {
    @Resource
    UserCLRMapper userCLRMapper;
    @Resource
    private UserClient userClient;
    @Resource
    private UserCLRItemRepository userCLRItemRepository;

    @Resource
    private ProductClient productClient;
    @Resource
    private Map<String, BaseStrategy> baseStrategyMap;

    /**
     * 添加点赞/收藏/转发
     * @param json
     * @param request
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String addUserCLR(JSONObject json, HttpServletRequest request) {
        JSONObject js = new JSONObject();
        //获取请求凭证,凭证中存放用户ID和用户名，存放格式为：userId_userName
        String secretToken = request.getHeader("secretToken");

        JSONObject j1 = new JSONObject();
        j1.put("redis_key",secretToken);
        //获取redis中缓存的token
        String o = userClient.getRedisData(j1);
        if (null!=o) {
            //截取请求头中存储的用户ID
            int secretTokenIndex = secretToken.lastIndexOf(":");
            String userIdSub = secretToken.substring(secretTokenIndex + 1);
            Integer userId = Integer.valueOf(userIdSub);//用户ID
            try {
                //前端参数
                Integer type = json.getInteger("obj_type");//对象类型：0商品 其他待定
                String objId = json.getString("obj_id");//评论的对象ID，例如：商品编码，视频ID
                Integer clrType = json.getInteger("clr_type");//操作类型：0点赞 1收藏 2转发

                JSONObject js1 = new JSONObject();
                js1.put("user_id",userId);

                //根据用户ID查询评论者信息
                String u = userClient.findById(js1);
                JSONObject j2 = JSONObject.parseObject(u);
                String data = j2.getString("data");

                //实体数据返回
                JSONObject j3 = JSONObject.parseObject(data);

                String userName = j3.getString("userName");
                String userHead = j3.getString("userHead");

                //list封装
                List<UserCLRBean> list = new ArrayList<>();
                
                //时间规格化
                SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String addTime = sf.format(new Date());

                //封装请求参数
                JSONObject jRating = new JSONObject();
                jRating.put("user_id",userId);
                jRating.put("obj_id",objId);
                jRating.put("obj_type",type);
                //获取打分数据
                int userRating = userClient.getUserRatingById(json);
                //转发没有取消的操作
                if (clrType==2){
                    //对象实例化
                    UserCLRBean clr = new UserCLRBean();
                    clr.setClrType(clrType);
                    clr.setObjType(type);
                    clr.setObjId(objId);
                    clr.setUserId(userId);
                    clr.setAddTime(addTime);

                    list.add(clr);
                    //es存储
                    userCLRItemRepository.save(clr);

                    //将分数加一
                    userRating = userRating+1;
                    jRating.put("user_rating",userRating);

                    //用户打分操作
                    userClient.addUserRating(jRating);
                }else {
                    //查询用户是否已操作过
                    UserCLRBean userCLRBean = userCLRMapper.getCLRByClrTypeAndObjIdAndObjTypeAndUserId(clrType, objId, type, userId);
                    if (null!=userCLRBean){
                        Integer clrType1 = userCLRBean.getClrType();
                        if (clrType1!=clrType){//执行添加即可
                            //对象实例化
                            UserCLRBean clr = new UserCLRBean();
                            clr.setClrType(clrType);
                            clr.setObjType(type);
                            clr.setObjId(objId);
                            clr.setUserId(userId);
                            clr.setAddTime(addTime);

                            list.add(clr);
                            //es存储
                            userCLRItemRepository.save(clr);

                            //将分数加一
                            userRating = userRating+1;
                            jRating.put("user_rating",userRating);

                            //用户打分操作
                            userClient.addUserRating(jRating);
                        }else {
                            //执行删除操作

                            //mysql删除
                            userCLRMapper.deleteByIdAndType(type,objId);

                            //es删除
                            userCLRItemRepository.deleteByObjIdAndObjType(type,objId);

                            //将分数加一
                            if (userRating>0){
                                userRating = userRating -1;
                            }
                            jRating.put("user_rating",userRating);

                            //用户打分操作
                            userClient.addUserRating(jRating);

                            // json封装
                            js.put("code", 200);
                            js.put("msg", "Success");
                        }
                    }else {
                        //对象实例化
                        UserCLRBean clr = new UserCLRBean();
                        clr.setClrType(clrType);
                        clr.setObjType(type);
                        clr.setObjId(objId);
                        clr.setUserId(userId);
                        clr.setAddTime(addTime);

                        list.add(clr);
                        //es存储
                        userCLRItemRepository.save(clr);

                        //将分数加一
                        userRating = userRating+1;
                        jRating.put("user_rating",userRating);

                        //用户打分操作
                        userClient.addUserRating(jRating);
                    }
                }
                if (list.size()>0){
                    //添加操作
                    int flag = userCLRMapper.addUserCLR(list);
                    if (flag<0){

                        // json封装
                        js.put("code",401);
                        js.put("msg","Fails");
                    }else {

                        // json封装
                        js.put("code", 200);
                        js.put("msg", "Success");

                        //转发不需要发消息通知
                        if (clrType!=2){

                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("obj_type",type);

                            String d = userClient.getDataNameAndDesc(jsonObject);
                            JSONObject j4 = JSONObject.parseObject(d);

                            String name = j4.getString("name");
                            String desc = j4.getString("desc");

                            //根据类型，获取相应信息
                            BaseStrategy baseStrategy = baseStrategyMap.get(name);
                            Map infos = baseStrategy.getInfos(objId,clrType);

                            String objTitle = String.valueOf(infos.get("objTitle"));
                            String proUserId = String.valueOf(infos.get("userId"));
                            String cover = String.valueOf(infos.get("cover"));
                            //详细信息
                            String contentInfo = "<div><p id='objId'>" + objId + "</p><p id='objType'>" + type + "</p><p id='objTitle'>" + objTitle + "</p><p id='cover'><img src='" + cover + "'></p></div>";
                            String usersInfo = "<div><p id='userId'>" + userId + "</p><p id='userName'>" + userName + "</p><p id='userHead'>" + userHead + "</p></div>";
                            String commentInfo = "";
                            if (clrType==0){
                                commentInfo = new String("<div><p id='contents'>点赞了你的"+desc+"</p></div>");
                            }
                            if (clrType==1){
                                commentInfo = new String("<div><p id='contents'>收藏了你的"+desc+"</p></div>");
                            }
                            //最终发送消息
                            String msg = contentInfo + usersInfo + commentInfo;
                            //给发布者发送消息通知
                            JSONObject j = new JSONObject();
                            j.put("user_id", proUserId);
                            j.put("msg", msg);
                            j.put("msg_type", 2);
                            j.put("f_user_id", 0);
                            userClient.sendPrivateMsg(j);
                        }
                    }
                }
            }catch (Exception e){
                js.put("code",500);
                js.put("msg",e.getMessage());
            }
        }else {
            js.put("code",400);
            js.put("msg","The Current Request is Invalid");
        }

        return JSONObject.toJSONString(js, SerializerFeature.WriteMapNullValue);
    }

    @Override
    public String getUserCLRById(JSONObject json) {
        JSONObject js = new JSONObject();
        //获取参数
        Integer userId = json.getInteger("user_id");
        String objId = json.getString("obj_id");
        Integer objType = json.getInteger("obj_type");
        Integer type = json.getInteger("clr_type");//标识符：0点赞 1收藏

        //查询
        Optional<UserCLRBean> clr = userCLRItemRepository.findAllByClrTypeAndObjIdAndObjTypeAndUserId(type, objId, objType, userId);
        if (clr.isPresent()){
            js.put("data",1);
        }else {
            js.put("data",0);
        }
        js.put("code",200);
        js.put("msg","Success");

        return JSONObject.toJSONString(js, SerializerFeature.WriteMapNullValue);
    }

    @Override
    public String delESUserCLR() {
        JSONObject js =  new JSONObject();
        userCLRItemRepository.deleteAll();
        // json封装
        js.put("code", 200);
        js.put("msg", "Success");
        return JSONObject.toJSONString(js, SerializerFeature.WriteMapNullValue);
    }
}
